package cn.stylefeng.guns.modular.basic.service.utils;

import cn.stylefeng.guns.tree.LayuiTree;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public final class TreeKit {


    public static List<LayuiTree> buildTree(Object startId, List<LayuiTree> all) {

        //rootNodes
        final List<LayuiTree> rootNodes = all.parallelStream().filter(it -> Objects.equals(startId, it.getParentId())).collect(Collectors.toList());
        List built = new ArrayList<>(rootNodes);

        for (LayuiTree rootNode : rootNodes) {
            rootNode.setChildren(buildChildren(rootNode.getValue(), built, all));
        }
        return rootNodes;
    }

    private static List<LayuiTree> buildChildren(Object parentId, List<LayuiTree> built, List<LayuiTree> all) {
        List<LayuiTree> me = new ArrayList<>();
        for (LayuiTree layuiTree : all) {
            if (built.contains(layuiTree)) {
                continue;
            }

            if (Objects.equals(parentId, layuiTree.getParentId())) {
                built.add(layuiTree);
                me.add(layuiTree);
                layuiTree.setChildren(buildChildren(layuiTree.getValue(), built, all));
            }
        }
        return me;
    }


    public static List<LayuiTree> combine(Collection<LayuiTree>... trees) {
        if (trees == null) {
            return null;
        }

        List<LayuiTree> root = new ArrayList<>(trees[0]);
        List<LayuiTree> current = root;

        if (trees.length == 1) {
            return root;
        }

        AtomicInteger depth = new AtomicInteger(0);

        for(int i =1;i<trees.length;i++) {
            List<LayuiTree> sub = new ArrayList<>(trees[i]);

            //有档案柜，档案室,二级树
            current.parallelStream().map(it -> {
//                it.setDisabled(true);
                final List<LayuiTree> two = sub.parallelStream().filter(c -> Objects.equals(it.getValue(), c.getParentId())).collect(Collectors.toList());
                it.setChildren(two);
                return it;
            }).count();

            current = sub;

            depth.incrementAndGet();

            current.parallelStream().forEach(it -> it.setDepth(depth.get()));
        }

        return root;
    }


}
